package com.szxy.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @Author:zwer
 * @Date:2020/5/24 20:26
 * @Description:com.szxy.forkjoin
 * @Version:1.0
 * Fork join 框架的简单使用
 **/
public class ForkJoinCalculation extends RecursiveTask<Long> {

    private long start;
    private long end;
    private static final long threshold = 10000L;

    public ForkJoinCalculation(long start, long end) {
        this.start = start;
        this.end = end;
    }

    public ForkJoinCalculation() {

    }

    @Override
    protected Long compute() {
        long diff = end - start;
        if (diff <= threshold) {
            long sum = 0L;
            for(long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else {
            long middle = (end + start)/2;
            ForkJoinCalculation left = new ForkJoinCalculation(start, middle);
            left.fork(); // 拆分成子任务
            ForkJoinCalculation right = new ForkJoinCalculation(middle + 1, end);
            right.fork(); // 拆分成子任务
            // 合并返回结果
            return left.join() + right.join();
        }
    }
}
